<template>
  <div>
    <el-drawer
      :title="$t('message.yxjh')"
      :visible.sync="isShowModal"
      :before-close="handleClose"
      size="920px"
    >
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="rules"
        label-width="auto"
        label-suffix="："
      >
        <div class="warnningTip">
          {{ $t('message.qfdxyc') }}
        </div>
        <el-form-item :label="$t('message.jhmc')" prop="name">
          <el-input
            v-model="param.name"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.jhmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.jsdx')" prop="type">
          <el-radio v-model="param.type" label="3">{{ $t('message.zdrq') }}</el-radio>
        </el-form-item>
        <el-form-item style="margin-top: -20px" prop="portraitId">
          <div class="portrayal_option">
            <div class="list">
              <div
                v-for="item in portrayalList"
                :key="item.portraitId"
                :class="{ active: item.portraitId === param.portraitId }"
                class="item"
                @click="portrayalClick(item.portraitId)"
              >
                {{ item.portraitName }}
              </div>
            </div>
            <div v-if="portrayalList.length < 20" class="fs12">
              {{ $t('message.bumanzu') }}，<span
                class="primaryColor pointer"
                @click="goToPortrayal"
              >{{ $t('message.qxzhx') }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.ffnr')" prop="grantObj">
          <div class="df_ac">
            <el-select
              v-model="param.grantType"
              class="mr10 w100"
              :disabled="param.num && param.id"
              @change="changeType"
            >
              <el-option :label="$t('message.yhj')" value="1" />
              <el-option :label="$t('message.tc')" value="2" />
            </el-select>
            <el-select
              v-if="param.grantType == '2'"
              v-model="param.grantObj"
              multiple
              :disabled="param.num && param.id"
              filterable
              :multiple-limit="5"
              class="w300"
              collapse-tags
              :placeholder="$t('message.qxztzzd5')"
            >
              <el-option
                v-for="item in mealList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-select
              v-if="param.grantType == '1'"
              v-model="param.grantObj"
              multiple
              :disabled="param.num && param.id"
              filterable
              :multiple-limit="5"
              class="w300"
              collapse-tags
              :placeholder="$t('message.qxzyhjzd5')"
            >
              <el-option
                v-for="item in couponList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <div v-if="param.grantType == '1'" class="fs12 ml10">
              {{ $t('message.dxfjbkcsy') }}
            </div>
            <div v-if="param.grantType == '2'" class="fs12 ml10">
              {{ $t('message.dxfjbkctc') }}
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.dxtz')">
          <el-radio
            v-model="param.smsSend"
            label="1"
            @change="changeSms"
          >{{ $t('message.bfsdx') }}</el-radio>
          <el-radio
            v-model="param.smsSend"
            label="0"
            @change="changeSms"
          >{{ $t('message.fsdxtz') }}</el-radio>
        </el-form-item>
        <el-form-item
          v-if="param.smsSend == '0'"
          :label="$t('message.dxnr')"
          :prop="param.templateFlag == '0' ? 'smsInfo' : 'tempId'"
        >
          <el-radio
            v-model="param.templateFlag"
            label="0"
            @change="changeSmsType"
          >{{ $t('message.zdynr') }}</el-radio>
          <el-radio
            v-model="param.templateFlag"
            label="1"
            @change="changeSmsType"
          >{{ $t('message.xzmoban') }}</el-radio>
          <el-select
            v-if="param.templateFlag == '1'"
            v-model="param.tempId"
            filterable
            class="w200"
          >
            <el-option
              v-for="item in smsTemplate"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
          <div class="warnningTip">
            {{ $t('message.dxaqzcjq') }}
          </div>
        </el-form-item>
        <el-form-item
          v-if="param.templateFlag == '0' && param.smsSend == '0'"
          prop="smsInfo"
        >
          <template>
            <div class="df_sb" style="margin-top: -20px">
              <span>{{ $t('message.dxqm') }}：[{{ shopInfo.smsSign }}]</span>
              <div class="df_ac">
                <el-input
                  v-if="param.isSave == '1'"
                  v-model="param.title"
                  placeholder="$t('message.qsr') + $t('message.mbbt')"
                  class="mr10"
                />
                <el-checkbox
                  v-model="param.isSave"
                  true-label="1"
                  false-label="0"
                >{{ $t('message.cwmb') }}</el-checkbox>
              </div>
            </div>
            <div class="sms_template">
              <el-input
                id="textareaId"
                v-model="param.smsInfo"
                type="textarea"
                :rows="6"
                maxlength="268"
                show-word-limit
                :placeholder="$t('message.qsrdxnr')"
              />
              <span class="fs12 placeholder9 rr">{{ $t('message.jsqhfr') }}</span>
            </div>
          </template>
        </el-form-item>
        <el-form-item
          v-if="param.templateFlag == '0' && param.smsSend == '0'"
          :label="$t('message.crspf')"
        >
          <div class="df_ac">
            <el-button
              @click="changeSysInfo('{memberName}')"
            >{{ $t('message.hymc') }}</el-button>
            <el-button
              class="mr10"
              @click="changeSysInfo('{gymName}')"
            >{{ $t('message.cgmc') }}</el-button>
            <el-select v-model="param.addressValue" @change="changeAddress">
              <el-option
                v-for="item in addressOption"
                :key="item.val"
                :label="item.name"
                :value="item.val"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item
          v-if="param.smsSend == '0' && param.templateFlag == '0'"
          style="margin-top: -20px"
        >
          <div class="df_sb">
            <span
              class="placeholder9"
            >{{ $t('message.wfwcn') }}</span>
            <span>{{ $t('message.dqygcs') }}{{ smsNum }}{{ $t('message.tdx') }}</span>
          </div>
        </el-form-item>
        <div class="df_ac mb20">
          <div class="property-title" style="margin: 0 20px 0 0">{{ $t('message.yxjh') }}</div>
          <span class="fs12">{{ $t('message.zxsjzxpc') }}；</span>
        </div>
        <el-form-item :label="$t('message.sczxsj')" prop="firstTime">
          <el-date-picker
            v-model="param.firstTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            :range-separator="$t('message.zhi')"
            clearable
            :disabled="param.num && param.id"
            :start-placeholder="$t('message.kssj')"
            :end-placeholder="$t('message.jssj')"
            class="w300"
          />
          <div class="fs12">
            {{ $t('message.sdsjsctfsj') }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.zxpc')" prop="interval">
          <span>{{ $t('message.mei') }} </span>
          <el-input
            v-model="param.interval"
            maxlength="50"
            class="w200"
            oninput="value=value.replace(/^0|[^0-9]/g, '')"
          />
          <span> {{ $t('message.tzxycmr1') }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.zxcs')" prop="allNum">
          <span>{{ $t('message.cxyx') }} </span>
          <el-input
            v-model="param.allNum"
            maxlength="50"
            oninput="value=value.replace(/^0|[^0-9]/g, '')"
            class="w200"
          />
          <span> {{ $t('message.cihou') }}，{{ $t('message.tzyx') }}；{{ $t('message.mrzxyc') }}</span>
        </el-form-item>
        <el-form-item :label="$t('message.zxdx')" prop="objType">
          <el-radio
            v-model="param.objType"
            label="1"
          >{{ $t('message.mztcdxzhy') }}</el-radio>
          <el-radio
            v-model="param.objType"
            label="2"
          >{{ $t('message.mztjdqbhy') }}</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            :loading="subLoading"
            type="primary"
            @click="onSubmit"
          >{{ $t('message.tj') }}</el-button>
          <el-button @click="handleClose">{{ $t('message.qx') }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  marketingPlanAdd,
  marketingPlanEdit,
  marketingPlanDetail,
  portrayalPostList,
  couponMealList,
  configDictionaries,
  smsTemplateOption,
  smsTemplateList,
  smsSignature
} from '@/api'
import dayjs from 'dayjs'
import _ from 'lodash'
export default {
  components: {},
  data() {
    return {
      param: {
        grantObj: [],
        type: '3',
        smsSend: '1',
        smsInfo: '',
        grantType: '1',
        templateFlag: '0',
        interval: '1',
        allNum: '1',
        objType: '1',
        portraitId: ''
      },
      subLoading: false,
      portrayalList: [],
      rules: {
        type: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        objType: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        portraitId: [{ required: true, message: this.$t('message.qxz') + this.$t('message.renqun'), trigger: 'blur' }],
        firstTime: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        templateFlag: [{ required: true, message: this.$t('message.qxz'), trigger: 'change' }],
        allNum: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        interval: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        tempId: [{ required: true, message: ' ', trigger: 'change' }],
        smsInfo: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        name: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        grantObj: [{ type: 'array', required: true, message: this.$t('message.qxz'), trigger: 'change' }]
      },
      couponList: [],
      mealList: [],

      smsTemplate: [],
      addressOption: [],
      shopInfo: {},
      isShowModal: false
    }
  },
  computed: {
    smsNum() {
      if (this.param.smsInfo) {
        return Math.ceil(this.param.smsInfo.length / 67)
      } else {
        return 0
      }
    }
  },
  created() {
    this.getPortrayalPostList()
    this.$set(this.param, 'firstTime', dayjs().format('YYYY-MM-DD HH:mm:ss'))
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { param } = this
          const fn = param.id ? marketingPlanEdit : marketingPlanAdd
          this.subLoading = true
          fn({ param }).then(res => {
            this.subLoading = false
            this.$message.success(this.$t('message.tjcg'))
            this.handleClose()
            this.$emit('success')
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    changeSms(val) {
      if (val === '0') {
        this.initSms() // 签名
      } else {
        this.$set(this.param, 'tempId', '')
      }
    },
    changeSmsType(val) {
      if (val === '0') {
        this.$set(this.param, 'tempId', '')
      } else {
        this.$set(this.param, 'smsInfo', '')
      }
    },
    getDetail(id) {
      marketingPlanDetail({ param: { id }}).then(res => {
        this.param = { ...this.param, ...res.record }
        this.changeType(this.param.grantType, false)
        this.changeSms(this.param.smsSend)
        if (res.record.tempId) {
          this.$set(this.param, 'templateFlag', '1')
        } else {
          this.$set(this.param, 'templateFlag', '0')
        }
        // console.log(this.param)
      })
    },
    changeSysInfo(val) {
      const smsInfo = this.param.smsInfo || ''
      const textareaEle = document.querySelector('#textareaId')
      const startPos = textareaEle.selectionStart
      if (startPos || startPos === 0) {
        const arr = smsInfo.split('')
        arr.splice(startPos, 0, `${val}`)
        this.$set(this.param, 'smsInfo', arr.join(''))
      } else {
        this.$set(this.param, 'smsInfo', smsInfo + `${val}`)
      }
    },
    changeAddress(val) {
      smsTemplateOption({ param: { path: val }}).then(res => {
        this.changeSysInfo(res.record.miniProgramLink)
      })
    },
    initSms() {
      smsSignature({ param: {}}).then(res => {
        this.shopInfo = res.record
      })
      smsTemplateList({ param: { smsType: '1', smsStatus: '1', smsEnable: '0' }}).then(res => {
        this.smsTemplate = res.recordList
      })
      configDictionaries({ param: { codes: 'WX_URL' }}).then(res => {
        this.addressOption = JSON.parse(res.recordList[0].val)
      })
    },
    changeType(val, flag = true) {
      if (val === '1') {
        couponMealList({ param: { type: 1 }, userId: sessionStorage.getItem('userId') }).then(res => {
          this.couponList = res.recordList || []
        })
      }
      if (val === '2') {
        couponMealList({ param: { type: 2 }}).then(res => {
          this.mealList = res.recordList || []
        })
      }
      if (flag) {
        this.$set(this.param, 'grantObj', [])
      }
    },
    getPortrayalPostList() {
      portrayalPostList({ param: {}}).then(res => {
        this.portrayalList = res.recordList || []
      })
    },
    portrayalClick(id) {
      this.$set(this.param, 'portraitId', id)
      this.$refs.form.clearValidate()
    },
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    },
    goToPortrayal() {
      this.handleClose()
      this.$emit('openPortrayal')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.portrayal_option {
  background-color: #f1f3f9;
  border-radius: 2px;
  padding: 8px;
  padding-bottom: 40px;
  .list {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -4px;
    .item {
      line-height: 20px;
      margin: 3px 4px;
      padding: 4px 8px;
      border-radius: 4px;
      border: 1px solid #e4e4e4;
      color: #999999;
      cursor: pointer;
    }
    .active {
      border: 1px solid $primaryColor;
      color: $primaryColor;
    }
  }
  .fs12 {
    position: absolute;
    left: 4px;
    bottom: 4px;
    line-height: 16px;
  }
}
.sms_template {
  position: relative;
  .el-textarea {
    padding-bottom: 30px;
  }
  .rr {
    position: absolute;
    left: 4px;
    bottom: 16px;
    line-height: 16px;
  }
}
</style>
